package com.admin.controller;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.admin.controller.from.FunctionFromBean;
import com.admin.model.RoleFunction;
import com.admin.model.Sys_Function;

public class FunctionController extends BaseController {

	public void index() {
		loadMain();
	}

	/**
	 * 加载数据
	 */
	public void loadMain() {
		try {
			
		String type = getPara("type");
		setAttr("type", type);
		List<Sys_Function> sf = Sys_Function.dao.query(new String[]{"parent=0"});
		List<FunctionFromBean> ffbs = new ArrayList<FunctionFromBean>();
		for (Sys_Function s : sf) {
			FunctionFromBean bean = new FunctionFromBean();
			bean.setSf(s);//父级菜单
			bean.setSfs(Sys_Function.dao.query(new String[]{"parent="+s.getLong("id")}));//子菜单
			ffbs.add(bean);
		}
		setAttr("functions",ffbs);
		render("/jsp/function/function_main.jsp");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 异步请求数据
	 */
	@SuppressWarnings("unchecked")
	public void treeData() {
		try {
			String roleId = getPara("roleId");
			List<Sys_Function> list = new ArrayList<Sys_Function>();
			JSONObject parentJson = new JSONObject();
			parentJson.put("id", "0");
			parentJson.put("pid", "-1");
			parentJson.put("name", "所有权限");
			parentJson.put("open", true);
//			long count = RoleFunction.dao.getCount(new String[]{"role_id='"+ roleId +"'"});
//			if(count > 0){
//				parentJson.put("checked", true);
//			}
			List<RoleFunction> roleFuns = RoleFunction.dao.query(new String[]{"role_id='"+ roleId +"'"});
			if(null != roleFuns && roleFuns.size() > 0){
				parentJson.put("checked", true);
			}
			list = Sys_Function.dao.list(new String[]{"parent = 0","del = 0"});
			JSONArray children = Sys_Function.dao.listToJson(list,roleFuns);
			parentJson.put("children", children);
			renderJson(parentJson);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(), e);
		}
	}

	/**
	 * 添加功能
	 */
	public void addFunction() {
		render("/jsp/function/saveorupdate.jsp");
	}

	/**
	 * 逻辑删除
	 */
	public void deleteFunction() {
		Integer id = this.getParaToInt("id");
		Sys_Function.dao.LogicDel(id);
		loadMain();
	}

	/**
	 * 修改功能
	 */
	public void updateFunction() {
		render("/jsp/function/saveorupdate.jsp");
	}
}
